package com.adtec.yxdemo.filelanding.service;

import com.adtec.yxdemo.utils.FileLandUtil;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;

/**
 * 文件打包
 */
public class YxFileComService {
    public void FilePack() {
        Path path1 = Paths.get("D:\\001\\003\\MC002.dat");
        Path path2 = Paths.get("D:\\001\\003\\MC002.ind");
        Path path3 = Paths.get("D:\\001\\003\\MC003.dat");
        Path path4 = Paths.get("D:\\001\\003\\MC003.ind");
        Path path5 = Paths.get("D:\\001\\003\\MC004.dat");
        Path path6 = Paths.get("D:\\001\\003\\MC004.ind");
        Path path7 = Paths.get("D:\\001\\003\\MC005.dat");
        Path path8 = Paths.get("D:\\001\\003\\MC005.ind");
        List<Path> paths = Arrays.asList(path1, path2, path3, path4, path5, path6, path7, path8);
        Path outputPath = Paths.get("D:\\001\\003\\001003" + FileLandUtil.getDate() + ".tar.gz");
        try (OutputStream fOut = Files.newOutputStream(outputPath);
             BufferedOutputStream buffOut = new BufferedOutputStream(fOut);
             GzipCompressorOutputStream gzOut = new GzipCompressorOutputStream(buffOut);
             TarArchiveOutputStream tOut = new TarArchiveOutputStream(gzOut)) {

            //遍历文件list
            for (Path p : paths) {
                //该文件不是目录或者符号链接
                if (!Files.isRegularFile(outputPath)) {
                    throw new IOException("Support only file!");
                }
                //将该文件放入tar包，并执行gzip压缩
                TarArchiveEntry tarEntry = new TarArchiveEntry(
                        outputPath.toFile(),
                        outputPath.getFileName().toString());

                tOut.putArchiveEntry(tarEntry);
                Files.copy(outputPath, tOut);

                tOut.closeArchiveEntry();
            }
            //for循环完成之后，finish-tar包输出流
            tOut.finish();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

